import { isObjectNull } from './EmptyUtil'

export function formatNumber (str, defaultNum = 0) {
  if (isObjectNull(str)) {
    return defaultNum
  }
  const tmp = Number(str)
  if (isNaN(tmp)) { return defaultNum } else { return tmp }
}

export function getPercentString (n) {
  const tmp = formatNumber(n, 0)
  return fixFloat((tmp * 100), 2, true) + '%'
}

/**
 * 保留float型的小数位数 去掉末尾的0
 * num 保留的位数  默认2位
 * isRound 是否四舍五入
 */
export function fixFloat (f, num = 2, isRound = false) {
  const ppp = Math.pow(10, num)
  const tmpFloat = f * ppp
  let tmpInt = 0
  if (isRound) {
    tmpInt = Math.round(tmpFloat)
  } else {
    tmpInt = Math.floor(tmpFloat)
  }
  return (tmpInt / ppp)
}
/**
 * 千分位(无小数)
 * @param {*} num
 */
export function micrometerLevelInt (num) {
  const reg = /\d{1,3}(?=(\d{3})+$)/g
  return (num + '').replace(reg, '$&,')
}
/**
 * 千分位(文件框输入时)
 * @param {*} num 数字
 * @param {int} xs 小数
 */
export function micrometerLevelInput (num, xs = 2) {
  num += ''
  let addDh = true// 输入已经有点了
  if (!num.includes('.')) {
    num += '.'
    addDh = false
  }
  // let temp=num.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
  let xsStr = ''// 补几位小数
  for (let y = 0; y < xs; y++) {
    xsStr += '\\d'
  }
  const re = new RegExp('(\\-)*(\\d+)\\.(' + xsStr + ').*', 'gim')
  let temp = num.replace(re, '$1$2.$3')// 只能输入N个小数
  temp = temp.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
    return $1 + ','
  })
  if (!addDh) {
    temp = temp.replace(/\.$/, '')
  }
  return temp
}
/**
 * 百分比(文件框输入时)
 * @param {*} num 数字
 * @param {int} xs 小数
 */
export function percentageInput (num, xs = 2) {
  num += ''
  let addDh = true// 输入已经有点了
  if (!num.includes('.')) {
    num += '.'
    addDh = false
  }
  // let temp=num.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
  let xsStr = ''// 补几位小数
  for (let y = 0; y < xs; y++) {
    xsStr += '\\d'
  }
  const re = new RegExp('(\\-)*(\\d+)\\.(' + xsStr + ').*', 'gim')
  let temp = num.replace(re, '$1$2.$3')// 只能输入N个小数
  if (!addDh) {
    temp = temp.replace(/\.$/, '')
  }
  return temp
}
